layui.use(['layer', 'form', 'table', 'admin', 'ax', 'func', 'laydate', 'upload'], function () {
    var $ = layui.$;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    var laydate = layui.laydate;
    var upload = layui.upload;
    //渲染时间选择框
    laydate.render({
        elem: '#loanDate',
        value: new Date(),
        tiger: 'click',
    });
    //监听单元格编辑
    table.on('edit(noticeTable)', function (obj) {
        var value = obj.value //得到修改后的值
            , data = obj.data //得到所在行所有键值
            , field = obj.field; //得到字段
        //编辑
        // var suo=data.flag;
        // if(suo==1){
        //     Feng.error("已报销,无法修改!");
        //     table.reload(Notice.tableId);
        //     return;
        // }

        //return false;
        //var layerIndex = layer.load(3);
        $.ajax({
            type: "PUT",
            url: "/flowInfo/update",
            datatype: "json",
            data: data,
            success: function (data) {
                // if(data==2){
                //     Feng.error("已报销，不能修改");
                //     table.reload(Notice.tableId);
                // }
                //Feng.success("修改成功！");
                table.reload(Notice.tableId);
            }, error: function () {
                Feng.error("修改失败！");
            }, complete: function (XHR, TS) {
                //layer.close(layerIndex);
                //50秒自动刷新一次
                //setTimeout(showTime,50000);
            }

        });
        //layer.msg('[ID: '+ data.id +'] ' + field + ' 字段更改为：'+ value);
    });
    /**
     * 系统管理--消息管理
     */
    var Notice = {
        tableId: "noticeTable"    //表格id
    };
    $("#condition").on("input", function (e) {
        //获取input输入的值
        Notice.search();
    });
    form.on('select(dm)', function (data) {
        Notice.search();
    });
    /**
     * 选中行效果
     */
    table.on('row(noticeTable)', function (obj) {
        $(obj.tr).siblings().css("background-color", "");
        obj.tr.css({"background-color": "#dadad9"});
    });
    /**
     * 检索借款人
     */
    var languageAjax = new $ax(Feng.ctxPath + "/flowInfo/borrowerInfo");
    var languageResult = languageAjax.start();

    $.each(languageResult, function (index, val) {
        $("#borrowerId").append("<option value='" + val.id + "'>" + val.name + "</option>");
    });
    form.render('select');

    /**
     * 获取已借贷款人
     */
    var borrowedAjax = new $ax(Feng.ctxPath + "/flowInfo/borrowed");
    var borrowedResult = borrowedAjax.start();
    $("#borrowed").append("<option value=''>" + borrowedResult.length + "</option>");
    $.each(borrowedResult, function (index, val) {
        $("#borrowed").append("<option value='" + val.id + "'>" + val.name + "</option>");
    });
    form.render('select');

    /**
     * 获取未借贷款人
     */
    var notBorrowedAjax = new $ax(Feng.ctxPath + "/flowInfo/notBorrowed");
    var notBorrowedResult = notBorrowedAjax.start();
    $("#notBorrowed").append("<option value=''>" + notBorrowedResult.length + "</option>");
    $.each(notBorrowedResult, function (index, val) {
        $("#notBorrowed").append("<option value='" + val.id + "'>" + val.name + "</option>");
    });
    form.render('select');
    /**
     * 初始化表格的列
     */
    Notice.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', align: "center", hide: true, sort: true, title: 'id'},
            //{field: 'borrower_id', align: "center",sort: true, title: 'borrower_id'},
            {align: 'center', type: "numbers", title: '序号'},
            {field: 'loan_date', align: "center", sort: true, title: '日期', width: 130},
            {field: 'name', align: "center", sort: false, title: '姓名', width: 80},
            {field: 'summary', align: "center", sort: false, title: '摘要', edit: 'text'},
            {field: 'debit', align: "center", sort: false, title: '借方', totalRow: true, width: 80},
            {field: 'credit', align: "center", sort: false, title: '贷方', totalRow: true, width: 80},
            {field: 'balance', align: "center", sort: true, title: '余额'},
            {field: 'bj', align: "center", sort: true, title: '借款本金', width: 110},
            {field: 'yll', align: "center", sort: true, title: '月利率'},
            {field: 'month', align: "center", sort: true, title: '还款月份', width: 110},
            {field: 'hkje', align: "center", sort: true, title: '应还款本金', width: 130},
            {field: 'lx', align: "center", sort: true, title: '应还款利息', width: 130},
            {field: 'yhkje', align: "center", sort: true, title: '已还款金额', width: 130, edit: 'text'},
            {field: 'remark', align: "center", sort: false, title: '备注', width: 100},
            {align: 'center', toolbar: '#tableBar', title: '操作', minWidth: 150}
        ]];
    };

    /**
     * 点击查询按钮
     */
    Notice.search = function () {
        var queryData = {};
        queryData['condition'] = $("#borrowerId").val();
        queryData['month'] = $("#loanDate").val();
        queryData['dm'] = $("#dm").val();
        queryData['status'] = $("#status").val();
        table.reload(Notice.tableId, {
            where: queryData, page: {curr: 1}
        });
    };

    function se(se) {
        Notice.search(se);
    }

    /**
     * 导出excel按钮
     */
    Notice.exportExcel = function () {
        var borrowerId = $("#borrowerId").val();
        //获取导出Excel的数据
        var url = Feng.ctxPath + "/flowInfo/listExport?borrowerId=" + borrowerId;
        location.href = url;

        // if (shopName == "" || shopName == undefined || shopName == null) {
        //     Feng.error("请先选择门店");
        // } else {
        //     //获取导出Excel的数据
        //     var url = Feng.ctxPath + "/flowInfo/listExport?borrowerId=" + borrowerId;
        //     location.href = url;
        // }
    };

    // 导出通讯录
    $('#btnExport').click(function () {
        Notice.exportExcel();
    });

    /**
     * 弹出添加通知
     */
    Notice.openAddNotice = function () {
        // var dm=$("#dm").val();
        // if(dm == ""){
        //     Feng.error("请选择店名!");
        //     return;
        // }
        var borrowerId = $("#borrowerId").val();
        if (borrowerId == "") {
            Feng.error("请选择借款人!");
            return;
        }
        var loanDate = $("#loanDate").val();
        var summary = $("#summary").val();
        var debit = $("#debit").val();
        var credit = $("#credit").val();
        var balance = $("#credit").val();
        var remark = $("#remark").val();
        var ajax1 = new $ax(Feng.ctxPath + "/flowInfo/add", function (data) {
            Feng.success("添加成功!");
            table.reload(Notice.tableId);
        }, function (data) {
            Feng.error("添加失败!" + data.responseJSON.message + "!");
        });
        ajax1.set("borrowerId", borrowerId);
        ajax1.set("loanDate", loanDate);
        ajax1.set("summary", summary);
        ajax1.set("debit", debit);
        ajax1.set("credit", credit);
        ajax1.set("balance", balance);
        ajax1.set("remark", remark);
        ajax1.start();
        // func.open({
        //     height: 1000,
        //     title: '添加巡店沟通',
        //     content: Feng.ctxPath + '/btyBorrowerFlowInfo/btyBorrowerFlowInfo_add',
        //     tableId: Notice.tableId
        // });
    };

    /**
     * 弹出分期添加
     */
    Notice.openAddFq = function () {
        func.open({
            height: 500,
            title: '添加分期借款',
            content: Feng.ctxPath + '/flowInfo/btyBorrowerFlowInfo_add',
            tableId: Notice.tableId
        });
        Notice.search();
    };

    /**
     * 修改还款状态
     */
    Notice.editStatus = function () {
        var checkRows = table.checkStatus(Notice.tableId);
        var data = checkRows.data;
        var ids = "";
        if (checkRows.data.length === 0) {
            Feng.error("请选择要批量修改的数据");
        } else {
            for (var i in data) {
                ids += data[i].id + ",";
            }
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/flowInfo/updateSome", function (data) {
                    Feng.success("修改成功!");
                    table.reload(Notice.tableId);
                }, function (data) {
                    Feng.error("修改失败!" + data.responseJSON.message + "!");
                });
                ajax.set("id", ids);
                ajax.start();
            };
            Feng.confirm("是否批量修改?", operation);
        }
    };
    /**
     * 弹出还款
     */
    Notice.openAddHk = function (data) {
        var flag = data.flag;
        if (flag == 1) {
            Feng.error("已还款完毕,请勿重复还款!");
            return;
        }
        func.open({
            height: 300,
            title: '还款',
            content: Feng.ctxPath + '/flowInfo/btyBorrowerFlowInfo_hk/' + data.id,
            tableId: Notice.tableId
        });
    };
    /**
     * 弹出添加通知
     */
    Notice.openImportNotice = function () {
        func.open({
            height: 200,
            title: '借贷款批量导入',
            content: Feng.ctxPath + '/flowInfo/upload',
            tableId: Notice.tableId
        });
    };
    /**
     * 点击删除通知
     *
     * @param data 点击按钮时候的行数据
     */
    Notice.onDeleteNotice = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/flowInfo/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(Notice.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    /**
     * 点击批量删除
     * @param data 点击按钮时候的行数据
     */
    Notice.batchDelete = function () {
        var checkRows = table.checkStatus(Notice.tableId);
        var data = checkRows.data;
        var ids = "";
        if (checkRows.data.length === 0) {
            Feng.error("请选择要批量删除的数据");
        } else {
            for (var i in data) {
                ids += data[i].id + ",";
            }
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/flowInfo/batchDelete", function (data) {
                    Feng.success("删除成功!");
                    table.reload(Notice.tableId);
                }, function (data) {
                    Feng.error("删除失败!" + data.responseJSON.message + "!");
                });
                ajax.set("ids", ids);
                ajax.start();
            };
            Feng.confirm("是否批量删除?", operation);
        }
    };
    /**
     * 点击修改档案
     *
     * @param data 点击按钮时候的行数据
     */
    Notice.onEditNotice = function (data) {
        func.open({
            height: 1000,
            title: '修改巡店',
            content: Feng.ctxPath + "/btyXdgt/btyXdgt_update/" + data.id,
            tableId: Notice.tableId
        });
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Notice.tableId,
        url: Feng.ctxPath + '/flowInfo/list',
        page: true,
        height: "full-129",
        cellMinWidth: 100,
        limit: 20,
        totalRow: true,
        cols: Notice.initColumn(),
        // done:function (res, curr, count) {
        //     //图片预览
        //     layer.photos({
        //         photos: '.show_img',
        //         anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
        //     });
        // }
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        Notice.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        Notice.openAddNotice();
    });
    // 批量删除按钮点击事件
    $('#btnDelete').click(function () {
        Notice.batchDelete();
    });

    // 分期添加按钮点击事件
    $('#btnFq').click(function () {
        Notice.openAddFq();
    });

    // 修改还款状态点击事件
    $('#btnUpdateStatus').click(function () {
        Notice.editStatus();
    });

    /**
     * 导入Excel
     */
    upload.render({
        elem: '#btnExcel'
        , url: '/flowInfo/import'
        , accept: "file"
        , exts: 'xls|xlsx|xlsm|xlt|xltx|xltm'
        , before: function () {

        }
        , done: function (res) {
            if (res.state == 0) {
                layer.msg('导入失败！', {icon: 1, time: 2000, shade: 0.2});
            }
            if (res == true) {
                layer.msg('导入成功！', {icon: 1, time: 2000, shade: 0.2});
                window.location.reload();
            }
        }
    });

    /**
     * 还款导入Excel
     */
    upload.render({
        elem: '#btnHk'
        , url: '/flowInfo/importHk'
        , accept: "file"
        , exts: 'xls|xlsx|xlsm|xlt|xltx|xltm'
        , before: function () {

        }
        , done: function (res) {
            if (res.state == 0) {
                layer.msg('导入失败！', {icon: 1, time: 2000, shade: 0.2});
            }
            if (res == true) {
                layer.msg('导入成功！', {icon: 1, time: 2000, shade: 0.2});
                window.location.reload();
            }
        }
    });


    // 工具条点击事件
    table.on('tool(' + Notice.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            Notice.onEditNotice(data);
        } else if (layEvent === 'delete') {
            Notice.onDeleteNotice(data);
        } else if (layEvent === 'hk') {
            Notice.openAddHk(data);
        } else if (layEvent === 'batchDelete') {
            Notice.batchDelete(data);
        }
    });
});

$(function () {
    $.ajax({
        type: "post",
        url: "/flowInfo/allMoney",
        datatype: "json",
        success: function (data) {
            $("#allMoney").val(data.toFixed(2));
        }

    });
});